<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >

  <div style="height: 50px;">
    <el-button @click="openDialog" :disabled="props.isDisabled">批量新增</el-button>
    <el-button @click="handleAdd"  :disabled="props.isDisabled">添加明细</el-button>
    <InventoryForm ref="formRefAdd" :productionOrderId="props.productionOrderId" @success="handleSuccess" />
    <InventoryForm2 ref="formRefAdd2" :productionOrderId="props.productionOrderId" @success2="handleSuccess2" />

  </div>

    <el-table :data="formData" class="-mt-10px" style="height: 280px;" border>
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="存货编码" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryCode`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryCode" placeholder="请输入存货编码"  @click="openDialog2($index)"   :disabled="props.isDisabled" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="存货名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryName`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryName" placeholder="请选择存货名称"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="规格型号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventorySpecModel`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventorySpecModel" placeholder="请输入规格型号"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryUnitName`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryUnitName" placeholder="请输入单位"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>


      <el-table-column label="货位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.locationId`" :rules="formRules.required" class="mb-0px!">
            <el-select v-model="row.locationName" placeholder="请选择货位号" :disabled="props.isDisabled" :loading="selectLoading"  filterable remote  @change="handleLocationChange($event, row)"  :remote-method="remoteLocation">
              <el-option
                v-for="item in locationList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>          
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.quantity`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.quantity" placeholder="请输入数量" :disabled="props.isDisabled" @input="calculateValues($index)"/>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="最大入库数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.maxQuantity`" :rules="formRules.maxQuantity" class="mb-0px!">
            <el-input v-model="row.maxQuantity" placeholder="请输入数量" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`"  class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" :disabled="props.isDisabled"/>
          </el-form-item>
        </template>
      </el-table-column>
       <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link :disabled="props.isDisabled">—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>

</template>
<script setup lang="ts">
import { Rdrecord10Api } from '@/api/wms/rdrecord10'
import InventoryForm from './Rdrecords10InventoryForm.vue';
import InventoryForm2 from './Rdrecords10InventoryForm2.vue';
import { ElMessage } from 'element-plus';
import { ProductionOrderApi, ProductionOrdersVO } from '@/api/wms/productionorder'
import { LocationApi, LocationVO } from '@/api/wms/location'

const props = defineProps<{
  pid: number | undefined  // 主表ID（主表的关联字段）
  isDisabled: boolean | undefined // 是否禁用表单
  productionOrderId: number | undefined  // 主表ID（主表的关联字段）
    
}>()
const formLoading = ref(false) // 表单的加载中
const selectLoading = ref(false) // 表单的加载中
const locationList = ref([] as LocationVO[]);

const formData = ref([])
const productionOrdersList = ref([] as ProductionOrdersVO[]); // 存货列表
const formRules = reactive({
  required: [{ required: true, message: '不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.pid,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      const initialData  = await Rdrecord10Api.getRdrecords10ListByPid(val)
      formData.value = await Promise.all(initialData.map(async (item) => {
        if (item.productionOrdersId) {
          const inventory = await ProductionOrderApi.getProductionOrdersById(item.productionOrdersId);
          const locationData = await LocationApi.getLocation(item.locationId)
          return {
            ...item,
            inventoryName: inventory.inventoryName,
            inventoryCode: inventory.inventoryCode,
            inventoryUnitName: inventory.inventoryUnitName,
            inventorySpecModel: inventory.inventorySpecModel,
            locationId: locationData.id,
            locationName: locationData.name,
            maxQuantity:inventory.quantity-inventory.inQuantity+item.quantity
          };
         
        }
      
        return item;
      
      }));

    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 查询存货 */
const remoteInventory = async () => {
  console.log(props.productionOrderId)
  if(props.productionOrderId==undefined)
  {
    ElMessage.warning(`请先选择生产任务单`);
  }else{
    productionOrdersList.value =await ProductionOrderApi.getProductionOrdersListByPid(props.productionOrderId);
  }
}

/** 查询货位 */
const remoteLocation = async () => {
  locationList.value =await LocationApi.getLocationSimpleList();
}


/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    orderId: undefined,
    sourceOrderId: undefined,
    productionOrdersId: undefined,
    batch: undefined,
    locationId: undefined,
    quantity: undefined,
    remark: undefined,
    sourceBatch: undefined,
    pid: undefined,
  }
  row.pid = props.pid
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}





defineExpose({ validate, getData })

//批量新增代码

const formRefAdd = ref(null); // 确保变量名唯一

const openDialog = () => {
  if(props.productionOrderId==undefined)
  {
    ElMessage.warning(`请先选择采购订单`);
  }else{
    // 打开弹窗的逻辑
    formRefAdd.value.open(); // 假设子组件有一个 open 方法
  }
};

const handleSuccess = (formData) => {
  // 处理 success 事件的逻辑
  console.log('Success event received with data:', formData)
  // 可以在这里调用 API 获取数据等
  const inventoryCodes = formData.inventoryCode;
  console.log('Selected inventory codes:', inventoryCodes);
  // 调用确认选择的方法
  confirmSelection(inventoryCodes);
};


/** 确认选择的存货编码 */
const confirmSelection = async (inventoryCodes: any[]) => {
  try {
    formLoading.value = true;
    const selectedInventoriesData = await Promise.all(inventoryCodes.map(async (id) => {
      const inventory = await ProductionOrderApi.getProductionOrdersById(id);
      return {
        id: undefined,
        pid: props.pid,
        productionOrdersId: inventory.id,
        inventoryName: inventory.inventoryName,
        inventoryCode: inventory.inventoryCode, 
        inventoryUnitName: inventory.inventoryUnitName,
        inventorySpecModel: inventory.inventorySpecModel,
        qty: undefined,
        maxQuantity:inventory.quantity-inventory.inQuantity,
        irate: undefined,
        price: undefined,
        itaxprice: undefined,
        imoney: undefined,
        itax: undefined,
        isum: undefined,
        cbmemo: undefined,
      };
    }));  
    formData.value.push(...selectedInventoriesData);
  } finally {
    formLoading.value = false;
    selectedInventories.value = []; // 重置选中的存货编码
  }
};

/** 处理存货名称选择变化 */
const handleInventoryChange = (value, row) => {
  const selectedInventory = productionOrdersList.value.find(item => item.id === value);
  if (selectedInventory) {
    row.productionOrdersId = selectedInventory.id;
    row.inventoryName = selectedInventory.inventoryName;
    row.inventoryCode = selectedInventory.inventoryCode;
    row.inventoryUnitName = selectedInventory.inventoryUnitName;
    row.inventorySpecModel = selectedInventory.inventorySpecModel;
    row.maxQuantity = selectedInventory.quantity-selectedInventory.inQuantity;


  }
};

/** 处理货位选择变化 */
const handleLocationChange = (value, row) => {
  const selectedInventory = locationList.value.find(item => item.id === value);
  if (selectedInventory) {
    row.locationId = selectedInventory.id;
    row.locationName = selectedInventory.name;
  }
};



const calculateValues = (index: number) => {
  const row = formData.value[index];
  if (row.quantity) {
    const quantity = parseFloat(row.quantity.toString());
    const maxQuantity = parseFloat(row.maxQuantity.toString());

    const maxQty = row.sumQty - row.useQty;

    if (quantity > maxQuantity) {
      ElMessage.warning(`数量不能超过 ${maxQuantity}`);
      row.quantity = maxQuantity;
    }
  }
};

// 点击弹出框内容

const formRefAdd2 = ref(null); // 确保变量名唯一
const selectedRowIndex = ref(-1); // 用于存储被点击行的索引

const openDialog2 = (index) => {
  if(props.productionOrderId==undefined)
  {
    ElMessage.warning(`请先选择采购订单`);
  }else{
    selectedRowIndex.value = index;
    // 打开弹窗的逻辑
    formRefAdd2.value.open(event);
    // formRefAdd.value.open(); // 假设子组件有一个 open 方法
  }
};

const handleSuccess2 = (getFormData) => {
  // 处理 success 事件的逻辑
  console.log('Success event received with data:', getFormData)
  // 可以在这里调用 API 获取数据等
  // 调用确认选择的方法
  // confirmSelection2(inventoryCodes);
  console.log('selectedRowIndex.value:', selectedRowIndex.value)

  if (selectedRowIndex.value !== -1) {
    console.log(formData.value[selectedRowIndex.value])
    formData.value[selectedRowIndex.value] = { ...getFormData.value, ...getFormData };
  }
};


</script>